import LPopup from "@/components/public/lPopup/lPopup";
import { defineComponent, reactive, ref } from "vue";
import styles from "./add.module.less"
import LForm, { LFormItem } from "@/components/public/lForm/lForm";
import { message } from "ant-design-vue";
import { $getPlanList, $insuranceGetList } from "@/api/search/search";
import _ from "lodash";
export default defineComponent({
  props: {
    service: {
      type: Object,
      required: true,
    },
  },
  emits: ["cancel", "confirm"],
  setup(props, { emit, expose }) {
    const tabs = reactive({
      list: [
        {
          key: 1,
          tab: "产品信息",
          pane: () => <ProductInfo />,
          confirmHandler: (e: any) => {
            confirmHandler(e);
          },
        },
        {
          key: 2,
          tab: "产品属性",
          pane: () => <ProductAttributes />,
          confirmHandler: (e: any) => {
            confirmHandler(e);
          },
        },
      ],
      actived: 1,
      id: "",
    } as any);
    const state_default = {
      form: {
        id: '',
        insurance_id: '',//产品
        // plan_code: '',   //方案id
        name: '',//名称
        code: '',//产品编码
        pic: '',//产品图片
        product_price: '',//产品最低价格
        sales_area: '',//销售地区
        insure_age: '',//承保年龄
        insure_day: '',//保险期间
        status: '',//状态
        price_unit: '',//单位价格
        liability_tag: [],//责任标签
      },
      selected_product: { //选中-产品
        value: '',
        label: '',
      },
      plan: { //选中-方案
        value: '',
        label: '',
      },
      age_start_unit: '',//承保年龄-开始单位
      age_start: '',//承保年龄-开始
      age_end: '',//承保年龄-结束
      age_end_unit: '',//承保年龄-结束单位
      age_end_max: false,//承保年龄结束是否无期限
      date_start: '',//承保期间开始
      date_end: '',//承保期间结束
      rules: {},
      product: [],//产品数组
      options: {
        plan: [],     //方案数组,
        age_start: [
          {
            label: '1',
            value: '1',
          },
          {
            label: '6',
            value: '6',
          },
          {
            label: '12',
            value: '12',
          },
          {
            label: '18',
            value: '18',
          },
          {
            label: '30',
            value: '30',
          },
        ],
        age_end: [
          {
            label: '6',
            value: '6',
          },
          {
            label: '12',
            value: '12',
          },
          {
            label: '18',
            value: '18',
          },
          {
            label: '无上限',
            value: '无上限',
          },
        ],
        date_start: [
          {
            label: '1天',
            value: '1天',
          },
          {
            label: '2天',
            value: '2天',
          },
          {
            label: '3天',
            value: '3天',
          },
          {
            label: '4天',
            value: '4天',
          },
          {
            label: '5天',
            value: '5天',
          },
          {
            label: '11天',
            value: '11天',
          },
          {
            label: '21天',
            value: '21天',
          },
        ],
        date_end: [
          {
            label: '1天',
            value: '1天',
          },
          {
            label: '2天',
            value: '2天',
          },
          {
            label: '3天',
            value: '3天',
          },
          {
            label: '4天',
            value: '4天',
          },
          {
            label: '10天',
            value: '10天',
          },
          {
            label: '20天',
            value: '20天',
          },
          {
            label: '40天',
            value: '40天',
          },
        ],
        unit: [    //单位
          {
            label: '天',
            value: "天",
          },
          {
            label: '岁',
            value: "岁",
          }
        ],
        liability_tag: [
          {
            label: '意外伤害',
            value: '意外伤害',
          },
          {
            label: '急性疾病风险',
            value: '急性疾病风险',
          },
          {
            label: '紧急医疗',
            value: '紧急医疗',
          },
          {
            label: '住院津贴',
            value: '住院津贴',
          },
          {
            label: '旅行不便',
            value: '旅行不便',
          },
          {
            label: '扩展风险运动',
            value: '扩展风险运动',
          },
          {
            label: '自费补偿',
            value: '自费补偿',
          },
          {
            label: '猝死',
            value: '猝死',
          },
          {
            label: '出行责任',
            value: '出行责任',
          },
        ]
      },
    }
    const state: any = reactive(
      _.cloneDeep(state_default)
    );
    const datestring = () => {
      return new Date().getTime();
    };
    const addPopupRef = ref(null as any);

    //打开弹窗
    const open = (e: any) => {
      if (e === undefined) {
        addPopupRef.value.open();
      } else {
        state.form = e;
        addPopupRef.value.open();
      }
      $insuranceGetList().then((res: any) => {
        state.product = res?.data?.map((x: any) => {
          return {
            label: x.name,
            value: x.id,
          };
        });
      });
    }
    //关闭弹窗
    const close = () => {
      addPopupRef.value.close();
    };
    //取消
    const cancelHandler = () => {
      addPopupRef.value.close();
    };
    //确认
    const confirmHandler = (e?: any) => {
      if (state.form.id) {
        props.service.edit(state.form).then((res: any) => {
          message.success("编辑产品成功");
          tabs.actived = 1;
          close();
          emit("confirm");
        }).finally(() => {
          e?.done?.();
        })
      } else {
        props.service.add(state.form).then((res: any) => {
          message.success("添加产品成功");
          tabs.actived = 1;
          close();
          emit("confirm");
        }).finally(() => {
          e?.done?.();
        })
      }
    }
    //选择产品change事件
    const productChange = () => {
      state.form.insurance_id = state.selected_product.value;
      state.form.name = state.selected_product.label.concat(state.plan.label);
      $getPlanList({ insurance_id: state.form.insurance_id }).then((res: any) => {
        state.options.plan = res?.data || [];
        console.log(res);
      })
    }
    //选择方案change事件
    const planChange = () => {
      console.log(state.plan);
      state.form.plan_code = state.plan.value;
      state.form.name = state.selected_product.label.concat(state.plan.label);
      console.log(state.form.plan_code);
    }
    expose({
      open,
      close,
    });
    //产品信息
    const ProductInfo = () => (
      <div class={styles['producttablePageEdit']}>
        <div style={{ width: "700px" }}>
          <LForm
            btns={["cancel", "confirm"]}
            v-model={state.form}
            onCancel={() => {
              cancelHandler();
            }}
            onConfirm={(e: any) => {
              tabs?.list
                ?.find((x: any) => x.key === tabs.actived)
                ?.confirmHandler(e);
            }}
          >
            <LFormItem label="产品" prop="">
              <a-select
                v-model:value={state.selected_product}
                options={state.product}
                labelInValue={true}
                style="width: 100%"
                placeholder="请选择产品"
                onChange={() => { productChange() }}
              ></a-select>
            </LFormItem>
            {/* <LFormItem label="方案" prop="">
              <a-select
                labelInValue={true}
                v-model:value={state.plan}
                options={state.options.plan}
                style="width: 250px"
                placeholder="请选择方案"
                onChange={() => { planChange() }}
              ></a-select>
            </LFormItem> */}
            <LFormItem label="产品名称" prop="name">
              <a-input
                style={{ width: '100%' }}
                v-model:value={state.form.name}
                placeholder="请输入产品名称"
              ></a-input>
            </LFormItem>
            <LFormItem label="最低价格:" prop="">
              <a-input
                placeholder="请输入价格"
                v-model={[state.form.product_price, "value"]}
              />
            </LFormItem>
            <LFormItem label="价格单位:" prop="">
              <a-input
                placeholder="请输入价格"
                v-model={[state.form.price_unit, "value"]}
              />
            </LFormItem>
          </LForm>
        </div>
      </div>
    )
    //承保年龄-结束Change
    const ageEndChange = () => {
      state.form.insure_age = String(state.age_start).concat(state.age_start_unit) + '-' + String(state.age_end).concat(state.age_end_unit);
      console.log(state.form.insure_age, '承保年龄')
    }
    //承保期间blur
    const dateEndBlur = () => {
      state.form.insure_day = state.date_start + '天' + '-' + state.date_end + '天';
      console.log(state.form.insure_day, '承保期间')
    }
    //产品属性
    const ProductAttributes = () => (
      <div class={styles['producttablePageEdit']}>
        <div style={{ width: "700px" }}>
          <LForm
            btns={["cancel", "confirm"]}
            v-model={state.form}
            onCancel={() => {
              cancelHandler();
            }}
            onConfirm={(e: any) => {
              tabs?.list
                ?.find((x: any) => x.key === tabs.actived)
                ?.confirmHandler(e);
            }}
          >
            <LFormItem label="产品编码" prop="">
              <a-input
                style={{ width: '100%' }}
                v-model:value={state.form.code}
                placeholder="请输入产品编码"
              ></a-input>
            </LFormItem>
            <LFormItem label="产品图片" prop="">
              <a-input
                style={{ width: '100%' }}
                v-model:value={state.form.pic}
                placeholder="请输入产品编码"
              ></a-input>
            </LFormItem>
            <LFormItem label="销售区域" prop="">
              <a-radio-group
                v-model:value={state.form.sales_area}
                name="radioGroup"
              >
                <a-radio value={'全国（不含港澳台）'}>全国（不含港澳台）</a-radio>
                <a-radio value={'当地'}>当地</a-radio>
              </a-radio-group>
            </LFormItem>
            <LFormItem label="承保年龄" prop="">
              <div class={styles.dists}>
                <div class={styles['dists-item-box']}>
                  <a-input-number
                    class={styles['dists-item']}
                    v-model:value={state.age_start}
                    min={1}
                    controls={false}
                    placeholder="请输入承保年龄"
                  ></a-input-number>
                  <a-select
                    style={{ margin: " 0 5px", width: '60px' }}
                    v-model:value={state.age_start_unit}
                    options={state.options.unit}
                  ></a-select>
                </div>
                <span style={"margin-left:8px"}>至</span>
                <div class={styles['dists-item-box']}>
                  <a-input-number
                    class={styles['dists-item']}
                    v-model:value={state.age_end}
                    placeholder="请输入承保年龄"
                    min={1}
                    controls={false}
                  ></a-input-number>
                  {
                    state.age_end_max ? "" :
                      <a-select
                        style={{ margin: " 0 5px", width: '60px' }}
                        v-model:value={state.age_end_unit} options={state.options.unit}
                        onChange={() => { ageEndChange() }}
                      ></a-select>
                  }
                </div>
              </div>
            </LFormItem>
            <LFormItem label="承保期间" prop="">
              <div class={styles.dists}>
                <div class={styles['dists-item-box']}>
                  {/* <a-select style="width: 100%" v-model:value={state.date_start} options={state.options.date_start} placeholder="">
                  </a-select> */}
                  <a-input-number
                    style="width: 100%"
                    v-model:value={state.date_start}
                    placeholder="请输入承保期间"
                    min={1}
                    controls={false}
                  ></a-input-number>
                </div>
                <span>（天）</span>
                <span style={"margin-left:8px"}>至</span>
                <div class={styles['dists-item-box']}>
                  <a-input-number
                    style="width: 100%"
                    v-model:value={state.date_end}
                    placeholder="请输入承保期间"
                    min={1}
                    controls={false}
                    onBlur={() => { dateEndBlur() }}
                  ></a-input-number>
                </div>
                <span>（天）</span>
              </div>
            </LFormItem>
            <LFormItem label="责任标签" prop="">
              <a-select
                v-model:value={state.form.liability_tag}
                options={state.options.liability_tag}
                mode="multiple"
                style="width: 100%"
              ></a-select>
            </LFormItem>
            <LFormItem label="状态" prop="">
              <a-radio-group
                v-model:value={state.form.status}
                name="radioGroup"
              >
                <a-radio value={1}>上架</a-radio>
                <a-radio value={0}>下架</a-radio>
              </a-radio-group>
            </LFormItem>
          </LForm>
        </div>
      </div>
    )
    const Components = () => (
      <LPopup
        title={state.form.id ? "编辑信息" : "添加信息"}
        ref={addPopupRef}
        onBeforeClose={() => {
          Object.entries(
            _.cloneDeep(state_default)
          ).forEach(item => {
            state[item[0]] = item[1];
            tabs.actived = 1;
          })
        }}
      >
        <div class={styles.producttablePageDetail}>
          <a-tabs
            class={styles.tabs}
            v-model={[tabs.actived, "activeKey"]}
            type="card"
            onChange={() => {
              console.log(123)
            }}
          >
            {tabs.list.map((x: any) => (
              <a-tab-pane class={styles["tab-pane"]} key={x.key} tab={x.tab}>
                {x.pane && x.pane()}
              </a-tab-pane>
            ))}
          </a-tabs>
        </div>
      </LPopup>
    );
    return {
      Components,
    }
  },
  render() {
    return <this.Components />;
  },
})